﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using Microsoft.VisualBasic.FileIO;
using Microsoft.Win32;
using WindowsHelper;
using IWshRuntimeLibrary;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using CharSet=System.Runtime.InteropServices.CharSet;
using ComInterfaceType=System.Runtime.InteropServices.ComInterfaceType;
using File=IWshRuntimeLibrary.File;
using LayoutKind=System.Runtime.InteropServices.LayoutKind;
using UnmanagedType=System.Runtime.InteropServices.UnmanagedType;
using System.Collections;
using Common;
using SKYPE4COMLib;
using Application=System.Windows.Forms.Application;
using System.Security;
using Narbware;
using Ini;
using WinControls.ListView;
using MessengerAPI;

namespace GlobalHooksTest
{
    public partial class PopUpForm : Form
    {
        public static string GetExeDir(string ExePath)
        {
            return Path.GetDirectoryName(ExePath);
        }
        SysImageList sysimage = new SysImageList(SysImageListSize.smallIcons);
        public static string ExePath = GetExeDir(Application.ExecutablePath);
        private string SkinDir = "Aero";
//        public  static string FolderIco = ExePath + "\\Skins\\" + SkinDir + "\\folder.png";
        public Bitmap Menu1S = null;
        public Bitmap PinS = null;
        public Bitmap PinClearS = null;
        public Bitmap UnPinClearS = null;
        public Bitmap UnPin = null;
        public static List<IntPtr> Handles;
        public static PerPixelAlphaForm G = null;
        public string FirefoxPath = "";
        public static string PinExePath = "";
        public static TreeListView TRV = null;
        public static int IsPinned = 0;
        public Skype Sky;
        public Messenger MSN;
        public static IniFile SettingsIni = null;
        public struct ButtonState
        {
            public ListViewItem l;
            public int Pinned;
        }
        

        private Image Fico = null;
        public IntPtr MediaPLayeH = IntPtr.Zero;
        public PopUpForm()
        {
            InitializeComponent();
            SettingsIni = new IniFile(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\SBar.ini");
            try
            {
                SkinDir = SettingsIni.IniReadValue("Main", "Skin");
            }
            catch
            {

            }
            if (SkinDir == "")
            {
                WindowsAPI.RECTW TaskHPos = new WindowsAPI.RECTW();
                WindowsAPI.GetWindowRect(frmSbarDevelopper.hTask, ref TaskHPos);
                if (TaskHPos.Height > 30)
                {
                    SkinDir = "Aero";
                }
                else
                {
                    SkinDir = "Aero16";
                }
            }
            Menu1S = new Bitmap(ExePath + "\\Skins\\" + SkinDir + "\\44.png");
            PinS = new Bitmap(ExePath + "\\Skins\\" + SkinDir + "\\Pin.png");
            PinClearS = new Bitmap(ExePath + "\\Skins\\" + SkinDir + "\\PinClear.png");
            UnPinClearS = new Bitmap(ExePath + "\\Skins\\" + SkinDir + "\\UnPinClear.png");
            UnPin = new Bitmap(ExePath + "\\Skins\\" + SkinDir + "\\UnPin.png");
            csSbar.Close();
            csSbar.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "\"" + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\SbarDB.mdb" + "\"";//""E:\Personal Projects\C#\Global Hook\GlobalHooksTest\bin\Debug\SbarDB.mdb"
            csSbar.Open();
            pinnedTableAdapter.Connection = csSbar;
            taskbarPinnedTableAdapterpu.Connection = csSbar;
            PopList();
            if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "skype")
            {
                Sky = new Skype();
            }
            if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "msnmsgr")
            {
                MSN = new Messenger(); 
            }
            if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "wmplayer")
            {
                MediaPLayeH = WindowsAPI.FindWindow("WMPlayerApp", "Windows Media Player");
            }



        }

        #region ShellLink
        [System.Runtime.InteropServices.DllImport("shfolder.dll", CharSet = CharSet.Auto)]
        internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);

        [Flags()]
        enum SLGP_FLAGS
        {
            /// <summary>Retrieves the standard short (8.3 format) file name</summary>
            SLGP_SHORTPATH = 0x1,
            /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>
            SLGP_UNCPRIORITY = 0x2,
            /// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary>
            SLGP_RAWPATH = 0x4
        }

        [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        struct WIN32_FIND_DATAW
        {
            public uint dwFileAttributes;
            public long ftCreationTime;
            public long ftLastAccessTime;
            public long ftLastWriteTime;
            public uint nFileSizeHigh;
            public uint nFileSizeLow;
            public uint dwReserved0;
            public uint dwReserved1;
            [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string cFileName;
            [System.Runtime.InteropServices.MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
            public string cAlternateFileName;
        }

        [Flags()]

        enum SLR_FLAGS
        {
            /// <summary>
            /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
            /// the high-order word of fFlags can be set to a time-out value that specifies the
            /// maximum amount of time to be spent resolving the link. The function returns if the
            /// link cannot be resolved within the time-out duration. If the high-order word is set
            /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
            /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
            /// duration, in milliseconds.
            /// </summary>
            SLR_NO_UI = 0x1,
            /// <summary>Obsolete and no longer used</summary>
            SLR_ANY_MATCH = 0x2,
            /// <summary>If the link object has changed, update its path and list of identifiers.
            /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
            /// whether or not the link object has changed.</summary>
            SLR_UPDATE = 0x4,
            /// <summary>Do not update the link information</summary>
            SLR_NOUPDATE = 0x8,
            /// <summary>Do not execute the search heuristics</summary>
            SLR_NOSEARCH = 0x10,
            /// <summary>Do not use distributed link tracking</summary>
            SLR_NOTRACK = 0x20,
            /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks
            /// removable media across multiple devices based on the volume name. It also uses the
            /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
            /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>
            SLR_NOLINKINFO = 0x40,
            /// <summary>Call the Microsoft Windows Installer</summary>
            SLR_INVOKE_MSI = 0x80
        }


        /// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>
        [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
        interface IShellLinkW
        {
            /// <summary>Retrieves the path and file name of a Shell link object</summary>
            void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);
            /// <summary>Retrieves the list of item identifiers for a Shell link object</summary>
            void GetIDList(out IntPtr ppidl);
            /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>
            void SetIDList(IntPtr pidl);
            /// <summary>Retrieves the description string for a Shell link object</summary>
            void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
            /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>
            void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
            /// <summary>Retrieves the name of the working directory for a Shell link object</summary>
            void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
            /// <summary>Sets the name of the working directory for a Shell link object</summary>
            void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
            /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>
            void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
            /// <summary>Sets the command-line arguments for a Shell link object</summary>
            void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
            /// <summary>Retrieves the hot key for a Shell link object</summary>
            void GetHotkey(out short pwHotkey);
            /// <summary>Sets a hot key for a Shell link object</summary>
            void SetHotkey(short wHotkey);
            /// <summary>Retrieves the show command for a Shell link object</summary>
            void GetShowCmd(out int piShowCmd);
            /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>
            void SetShowCmd(int iShowCmd);
            /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>
            void GetIconLocation([System.Runtime.InteropServices.Out(), System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,
                int cchIconPath, out int piIcon);
            /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>
            void SetIconLocation([System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
            /// <summary>Sets the relative path to the Shell link object</summary>
            void SetRelativePath([System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
            /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>
            void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
            /// <summary>Sets the path and file name of a Shell link object</summary>
            void SetPath([System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPWStr)] string pszFile);

        }

        [System.Runtime.InteropServices.ComImport, Guid("0000010c-0000-0000-c000-000000000046"),
        System.Runtime.InteropServices.InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IPersist
        {
            [System.Runtime.InteropServices.PreserveSig]
            void GetClassID(out Guid pClassID);
        }


        [ComImport, Guid("0000010b-0000-0000-C000-000000000046"),
        InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public interface IPersistFile : IPersist
        {
            new void GetClassID(out Guid pClassID);
            [PreserveSig]
            int IsDirty();

            [PreserveSig]
            void Load([In, MarshalAs(UnmanagedType.LPWStr)]
            string pszFileName, uint dwMode);

            [PreserveSig]
            void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName,
                [In, MarshalAs(UnmanagedType.Bool)] bool fRemember);

            [PreserveSig]
            void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName);

            [PreserveSig]
            void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);
        }

        const uint STGM_READ = 0;
        const int MAX_PATH = 260;

        // CLSID_ShellLink from ShlGuid.h 
        [
            ComImport(),
            Guid("00021401-0000-0000-C000-000000000046")
        ]
        public class ShellLink
        {
        }



        public static string ResolveShortcut(string filename)
        {
            ShellLink link = new ShellLink();
            ((IPersistFile)link).Load(filename, STGM_READ);
            // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.  
            // ((IShellLinkW)link).Resolve(hwnd, 0) 
            StringBuilder sb = new StringBuilder(MAX_PATH);
            WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
            ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
            return sb.ToString();
        }
        #endregion

         public static List<string> URL = new List<string>();
         public static List<string> Title = new List<string>();
         public static List<string> RecDocs = new List<string>();
        
        public static bool IsLeave = false;
        private  int MaxTextWidth = 0;
         void PopList()
        {
            List<string> ASSF = new List<string>();
            SysImageListHelper.SetListViewImageList(listView1, sysimage, false);
             string PathS = "";
             try
             {
                 PathS = WindowsAPI.GetWindowModuleFileName(Handles[0]);
             }
             catch
             {
                 PathS = PinExePath;
             }
             ASSF.Clear();
             if (Path.GetFileNameWithoutExtension(PathS) == "devenv")
             {
                 ASSF.Add(Path.GetDirectoryName(PathS).ToLower() + @"\vsta.exe");
                 ASSF.Add(PathS.ToLower());
                 ASSF.Add(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles).ToLower() + @"\microsoft shared\msenv\vslauncher.exe");
                 
             }
             else if (Path.GetFileNameWithoutExtension(PathS) == "bds")
             {
                 ASSF.Add(Path.GetDirectoryName(PathS).ToLower() + @"\bdslauncher.exe");
             }
             else
             {
                 ASSF.Add(PathS.ToLower());
             }
             listView1.ShowGroups = true;
             ListViewItem lit;
             listView1.Items.Clear();
             ListView.ListViewItemCollection lic = new ListView.ListViewItemCollection(listView1);
             lic.Clear();
             if (Path.GetFileName(PathS).ToLower() == "explorer.exe")
             {
                 foreach (string s in RecDocs)
                 {
                     string SD = ResolveShortcut(s);
                     if (SD != "")
                     {
                         if (Path.GetExtension(SD) == String.Empty)
                         {
                             string d = Path.GetDirectoryName(SD);

                             if (d == null)
                             {
                                 if (SD.Length > 20)
                                 {
                                     lit = new ListViewItem(SD.Substring(0, 20) + "...");
                                 }
                                 else
                                 {
                                     lit = new ListViewItem(SD);
                                 }
                                 if (listView1.Groups[1].Items.Count < 16)
                                 {
                                 lit.ImageIndex = sysimage.IconIndex(SD);
                                 lit.SubItems.Add("Explorer");
                                 lit.SubItems.Add(SD);
                                 lit.SubItems.Add("0");
                                 listView1.Groups[1].Items.Add(lit);
                                 
                                     lic.Add(lit); 
                                 }
                             }
                             else
                             {
                                 string[] splitPath = SD.Split('\\');
                                 if (splitPath[splitPath.Length - 1] != "")
                                 {
                                     if (splitPath[splitPath.Length - 1].Length > 20)
                                     {
                                         lit = new ListViewItem(splitPath[splitPath.Length - 1].Substring(0, 20) + "...");
                                     }
                                     else
                                     {
                                         lit = new ListViewItem(splitPath[splitPath.Length - 1]);
                                     }
                                     if (listView1.Groups[1].Items.Count < 16)
                                     {
                                         lit.ImageIndex =
                                             sysimage.IconIndex(
                                                 Environment.GetFolderPath(Environment.SpecialFolder.System), true);
                                         lit.SubItems.Add("Explorer");
                                         lit.SubItems.Add(SD + '\\');
                                         lit.SubItems.Add("0");
                                         listView1.Groups[1].Items.Add(lit);
                                         lic.Add(lit);
                                     }
                                 } 

                             }

                         }
                     }
                 }
             }
             else
             {
                 int i = 0;
                 foreach (string s in RecDocs)
                 {

                     string SS = ResolveShortcut(s);
                     if (true)
                     {
                         if (Path.GetFileName(PathS).ToLower() != "explorer.exe" &
                                          Path.GetFileName(PathS).ToLower() != "firefox.exe")
                         {
                             string sss = GetAssoc(Path.GetExtension(SS)).ToLower();
                             //                         if (Path.GetExtension(SS) == ".pas")
                             //                         {
                             if (ASSF.IndexOf(GetAssoc(Path.GetExtension(SS)).ToLower()) != -1)
                             {
                                 if (Path.GetFileNameWithoutExtension(SS).Length > 20)
                                 {
                                     lit = new ListViewItem(Path.GetFileNameWithoutExtension(SS).Substring(0, 20) + "...");
                                 }
                                 else
                                 {
                                     lit = new ListViewItem(Path.GetFileNameWithoutExtension(SS));
                                 }
                                 if (listView1.Groups[1].Items.Count < 16)
                                 {
                                     lit.ImageIndex = sysimage.IconIndex(SS);
                                     lit.SubItems.Add("");
                                     lit.SubItems.Add(SS);
                                     //                                 this.Controls.Add(IB);
                                     lit.SubItems.Add("0");
                                     lit.SubItems.Add("T");
                                     listView1.Groups[1].Items.Add(lit);
                                     lic.Add(lit);
                                 }
                             }
                             //                         }
                         }
                         else if (Path.GetFileName(PathS).ToLower() == "firefox.exe")
                         {
                             FirefoxPath = PathS;
                             listView1.Items.Clear();
                             foreach (string title in Title)
                             {

                                 if (title.Length > 30)
                                 {
                                     lit = new ListViewItem(title.Substring(0, 30) + "...");
                                 }
                                 else
                                 {
                                     lit = new ListViewItem(title);
                                 }
                                 if (listView1.Groups[1].Items.Count < 16)
                                 {
                                     lit.ImageIndex = sysimage.IconIndex(PathS);
                                     lit.SubItems.Add("Firefox");
                                     lit.SubItems.Add(URL[Title.IndexOf(title)]);
                                     lit.SubItems.Add("0");
                                     listView1.Groups[1].Items.Add(lit);
                                     lic.Add(lit);
                                 }
                             }
                         } 
                     }
                 }
             }
             string Line = "";
             List<string> ssr = new List<string>();
             ssr.Clear();
//             pinnedTableAdapter.Connection = csSbar;
             pinnedTableAdapter.FillBy(ds1.Pinned,
                                       Path.GetFileNameWithoutExtension(PathS));

             foreach (DataRow r in ds1.Pinned.Rows)
             {
                 string ss = r["PINNED_PATH"].ToString();
                 int LenghtS = 0;

                 if (Path.GetFileNameWithoutExtension(PathS).ToLower() != "firefox")
                 {
                     LenghtS = Path.GetFileNameWithoutExtension(ss).Length;
                 }
                 else
                 {
                     int hh = ss.IndexOf("*");
                     string st = ss.Substring(0, hh);
                     LenghtS = st.Length;  
                 }

                 if (LenghtS > 20)
                 {
                     if (Path.GetFileNameWithoutExtension(PathS).ToLower() != "explorer")
                     {
                         if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "firefox")
                         {
                             int h = ss.IndexOf("*");
                             string s = ss.Substring(0, h);
                             lit = new ListViewItem(s.Substring(0, 20) + "..."); 
                         }
                         else
                         {
                             lit = new ListViewItem(Path.GetFileNameWithoutExtension(ss).Substring(0, 20) + "...");
                         }
                     }
                     else
                     {
                         string[] splitPath = ss.Split('\\');
                         string Dirname = "";
                         if (splitPath[splitPath.Length - 1] == "")
                         {
                             Dirname = splitPath[splitPath.Length - 2];
                         }
                         else
                         {
                             Dirname = splitPath[splitPath.Length - 1];
                         }
                         lit = new ListViewItem(Dirname.Substring(0, 20) + "...");
                     }
                 }
                 else
                 {
                     if ((Path.GetFileNameWithoutExtension(PathS).ToLower() != "explorer"))
                     {
                         if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "firefox")
                         {
                             int h = ss.IndexOf("*");
                             string s = ss.Substring(0, h);
                             lit = new ListViewItem(s.Substring(0, 20) + "...");
                         }
                         else
                         {
                             lit = new ListViewItem(Path.GetFileNameWithoutExtension(ss));
                         }
                     }
                     else
                     {
                         string[] splitPath = ss.Split('\\');
                         string Dirname = "";
                         if (splitPath[splitPath.Length - 1] == "")
                         {
                             Dirname = splitPath[splitPath.Length - 2];
                         }
                         else
                         {
                             Dirname = splitPath[splitPath.Length - 1];
                         }
                         lit = new ListViewItem(Dirname);
                     }
                 }

                 if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "explorer")
                 {
                     lit.SubItems.Add("explorer");
                     if (ss.Length < 4)
                     {
                         lit.ImageIndex = sysimage.IconIndex(ss);
                     }
                     else
                     {
                         lit.ImageIndex = sysimage.IconIndex(Environment.GetFolderPath(Environment.SpecialFolder.System),true); 
                     }
                     
                 }
                 else if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "firefox")
                 {
                     lit.SubItems.Add("firefox");
                     lit.ImageIndex = sysimage.IconIndex(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                 }
                 else
                 {
                     lit.SubItems.Add(""); 
                     lit.ImageIndex = sysimage.IconIndex(ss);
                 }
                 if ((Path.GetFileNameWithoutExtension(PathS).ToLower() == "firefox"))
                 {
                     int h = ss.IndexOf("*");
                     string s = ss.Substring(0, h);
                     string sp = ss.Substring(h);
                     lit.SubItems.Add(s);
                     lit.SubItems.Add("1");
                     lit.SubItems.Add("");
                     lit.SubItems.Add(sp);
                 }
                 else
                 {
                     lit.SubItems.Add(ss);
                 }
                 lit.SubItems.Add("1");
                 listView1.Groups[0].Items.Add(lit);
                 lic.Add(lit);
             }

             if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "firefox")
             {
                 ListViewItem LNT = new ListViewItem("Open New Tab");
                 LNT.SubItems.Add("firefox");
                 LNT.ImageIndex = sysimage.IconIndex(PathS);
                 LNT.SubItems.Add("-new-tab ");
                 LNT.SubItems.Add("0");
                 LNT.Group = listView1.Groups[2];
                 ListViewItem LNW = new ListViewItem("Open New Window");
                 LNW.ImageIndex = sysimage.IconIndex(PathS);
                 LNW.SubItems.Add("firefox");
                 LNW.SubItems.Add("-new-window ");
                 LNW.SubItems.Add("0");
                 LNW.Group = listView1.Groups[2];
                 lic.Add(LNT);
                 lic.Add(LNW);

             }
             if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "skype")
             {
                 listView1.SmallImageList = CustomImagelist;
                 ListViewItem LNT1 = new ListViewItem("Online");
                 LNT1.SubItems.Add("skype");
                 LNT1.ImageIndex = 0;
                 LNT1.SubItems.Add("O");
                 LNT1.SubItems.Add("0");
                 LNT1.Group = listView1.Groups[2];
                 ListViewItem LNT2 = new ListViewItem("Away");
                 LNT2.SubItems.Add("skype");
                 LNT2.ImageIndex = 1;
                 LNT2.SubItems.Add("A");
                 LNT2.SubItems.Add("0");
                 LNT2.Group = listView1.Groups[2];
                 ListViewItem LNT3 = new ListViewItem("NA");
                 LNT3.SubItems.Add("skype");
                 LNT3.ImageIndex = 2;
                 LNT3.SubItems.Add("NA");
                 LNT3.SubItems.Add("0");
                 LNT3.Group = listView1.Groups[2];
                 ListViewItem LNT4 = new ListViewItem("Invisible");
                 LNT4.SubItems.Add("skype");
                 LNT4.ImageIndex = 3;
                 LNT4.SubItems.Add("I");
                 LNT4.SubItems.Add("0");
                 LNT4.Group = listView1.Groups[2];
                 ListViewItem LNW1 = new ListViewItem("Offline");
                 LNW1.ImageIndex = 4;
                 LNW1.SubItems.Add("skype");
                 LNW1.SubItems.Add("F");
                 LNW1.SubItems.Add("0");
                 LNW1.Group = listView1.Groups[2];
                 lic.Add(LNT1);
                 lic.Add(LNT2);
                 lic.Add(LNT3);
                 lic.Add(LNT4);
                 lic.Add(LNW1);
             }
             if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "msnmsgr")
             {
                 listView1.SmallImageList = CustomImagelist;
                 ListViewItem LNT1 = new ListViewItem("Online");
                 LNT1.SubItems.Add("msn");
                 LNT1.ImageIndex = 6;
                 LNT1.SubItems.Add("O");
                 LNT1.SubItems.Add("0");
                 LNT1.Group = listView1.Groups[2];
                 ListViewItem LNT2 = new ListViewItem("Away");
                 LNT2.SubItems.Add("msn");
                 LNT2.ImageIndex = 7;
                 LNT2.SubItems.Add("A");
                 LNT2.SubItems.Add("0");
                 LNT2.Group = listView1.Groups[2];
                 ListViewItem LNT3 = new ListViewItem("Busy");
                 LNT3.SubItems.Add("msn");
                 LNT3.ImageIndex = 8;
                 LNT3.SubItems.Add("NA");
                 LNT3.SubItems.Add("0");
                 LNT3.Group = listView1.Groups[2];
                 ListViewItem LNT4 = new ListViewItem("Appear Offline");
                 LNT4.SubItems.Add("msn");
                 LNT4.ImageIndex = 9;
                 LNT4.SubItems.Add("I");
                 LNT4.SubItems.Add("0");
                 LNT4.Group = listView1.Groups[2];
                 lic.Add(LNT1);
                 lic.Add(LNT2);
                 lic.Add(LNT3);
                 lic.Add(LNT4);
             }
             if (Path.GetFileNameWithoutExtension(PathS).ToLower() == "wmplayer")
             {
                 listView1.SmallImageList = CustomImagelist;
                 ListViewItem LNT1 = new ListViewItem("Play/Pause");
                 LNT1.SubItems.Add("mplay");
                 LNT1.ImageIndex = 11;
                 LNT1.SubItems.Add("P");
                 LNT1.SubItems.Add("0");
                 LNT1.Group = listView1.Groups[2];
                 ListViewItem LNT2 = new ListViewItem("Stop");
                 LNT2.SubItems.Add("mplay");
                 LNT2.ImageIndex = 12;
                 LNT2.SubItems.Add("S");
                 LNT2.SubItems.Add("0");
                 LNT2.Group = listView1.Groups[2];
                 lic.Add(LNT1);
                 lic.Add(LNT2);
             }
             


//            Bitmap b = new Bitmap(FolderIco);
//            Graphics g = Graphics.FromImage(b);
            foreach (ListViewItem li in listView1.Items)
            {
                if (li.Group != listView1.Groups[2])
                {
                    Bitmap UnPinClearB = new Bitmap(UnPinClearS);
                    PictureBox T = new PictureBox();
                    T.SizeMode = PictureBoxSizeMode.AutoSize;
                    ButtonState BS = new ButtonState();
                    BS.Pinned = Convert.ToInt32(li.SubItems[3].Text);
                    BS.l = li;
                    this.Controls.Add(T);
                    T.Location = new Point(174, listView1.GetItemRect(li.Index).Top);
                    T.BringToFront();
                    T.Tag = BS;
                    T.MouseEnter += T_MouseHover;
                    T.MouseLeave += new EventHandler(T_MouseLeave);
                    T.Click += new EventHandler(T_Click);
                    if (li.SubItems[3].Text == "0")
                    {
                        T.Image = UnPinClearB;
                    }
                    else
                    {
                        T.Image = PinClearS;
                    } 
                }
//                UnPinClearB.Dispose();
//                if ((int)g.MeasureString(li.Text,listView1.Font).Width > MaxTextWidth)
//                {
//                    MaxTextWidth = (int)g.MeasureString(li.Text, listView1.Font).Width;
//                }
            }
            ListViewItem LL = new ListViewItem("Open New");
            if (listView1.SmallImageList != CustomImagelist)
            {
                LL.ImageIndex = sysimage.IconIndex(PathS); 
            }
            else
            {
                if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "skype")
                {
                    LL.ImageIndex = 5; 
                }
                else if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "wmplayer")
                {
                    LL.ImageIndex = 13;  
                }
                else
                {
                  LL.ImageIndex = 10;  
                }
            }
            LL.SubItems.Add("OpenNew");
            LL.Group = listView1.Groups[3];
            ListViewItem LC = new ListViewItem("Close All");
            if (listView1.SmallImageList != CustomImagelist)
            {
                LC.ImageIndex = sysimage.IconIndex(PathS); 
            }
            else
            {
                if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "skype")
                {
                    LC.ImageIndex = 5;
                }
                else if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "wmplayer")
                {
                    LC.ImageIndex = 13;  
                }
                else
                {
                    LC.ImageIndex = 10;  
                }
//                LC.ImageIndex = 5;  
            }
            LC.SubItems.Add("SysClose");
            LC.Group = listView1.Groups[3];
             string PinText = "Pin to taskbar";
             if (IsPinned == 1)
             {
                 PinText = "Unpin from taskbar";
             }
             ListViewItem LP = new ListViewItem(PinText);
            if (listView1.SmallImageList != CustomImagelist)
            {
                LP.ImageIndex = sysimage.IconIndex(PathS);
            }
            else
            {
                if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "skype")
                {
                    LP.ImageIndex = 5;
                }
                else if (Path.GetFileNameWithoutExtension(PinExePath).ToLowerInvariant() == "wmplayer")
                {
                    LP.ImageIndex = 13;  
                }
                else
                {
                    LP.ImageIndex = 10;  
                }
//                LP.ImageIndex = 5;
            }
            LP.SubItems.Add("PinTaskbar");
            LP.Group = listView1.Groups[3];
            listView1.Items.Add(LP);
            listView1.Items.Add(LL);
            listView1.Items.Add(LC);
            foreach (ListViewItem li in listView1.Items)
            {
                if (li.Group == listView1.Groups[3])
                {
                    if (li.SubItems[1].Text == "PinTaskbar")
                    {
                        Bitmap UnPinClearB = new Bitmap(UnPinClearS);
                        PictureBox T = new PictureBox();
                        T.Name = "Pin";
                        T.SizeMode = PictureBoxSizeMode.AutoSize;
                        ButtonState BS = new ButtonState();
                        BS.Pinned = IsPinned;
                        BS.l = li;
                        this.Controls.Add(T);
                        T.Location = new Point(174, listView1.GetItemRect(li.Index).Top);
                        T.BringToFront();
                        T.Tag = BS;
                        T.MouseEnter += T_MouseHover;
                        T.MouseLeave += new EventHandler(T_MouseLeave);
                        T.Click += new EventHandler(T_Click);
                        if (IsPinned != 1)
                        {
                            T.Image = UnPinClearB;
                        }
                        else
                        {
                            T.Image = PinClearS;
                        } 
                    }
                }
                //                UnPinClearB.Dispose();
                //                if ((int)g.MeasureString(li.Text,listView1.Font).Width > MaxTextWidth)
                //                {
                //                    MaxTextWidth = (int)g.MeasureString(li.Text, listView1.Font).Width;
                //                }
            }
//            b.Dispose();
//            g.Dispose();
            
            if (MaxTextWidth < 150)
            {
                listView1.Width = 195; 
            }
            else
            {
//                listView1.Width = MaxTextWidth + 25;
                listView1.Width = 195; 
            }
             this.Width = listView1.Width;
             
//             imageButton2.Width = listView1.Width;

             int H = 0;
             int W = 0;
             int GH = 0;
             int Div = 0;
             int Gheight = 0;
             
             foreach (ListViewGroup gr in listView1.Groups)
             {
                 if (gr.Items.Count > 0)
                 {
                     GH++; 
                 }
             }
             if (GH == 1)
             {
                 Div = 3;
             }
             else
             {
                 Div = 1;
             }
             if (sv.OSMajorVersion != 6)
             {
                 Gheight = 36;
             }
             
             else
             {
                 Gheight = listView1.GetItemRect(0).Height + Div + 5;
             }
             if (listView1.Items.Count != 0)
             {
                 
                 listView1.Visible = true;
//                 imageButton2.Margin = new Padding(3,0,3,0);
//                 listView1.Height = listView1.Items.Count * 18 + 12 + listView1.Groups.Count * 22;
                 listView1.Size = new Size(listView1.Width, listView1.Items.Count * (listView1.GetItemRect(0).Height + Div) + (GH - 1)* 5 + GH * (Gheight) + 3);
                 W = listView1.Width + 90;
                 H = listView1.Height + 60;
             }
             else
             {
                 listView1.Height = 1;
//                 imageButton2.Margin = new Padding(3, 3, 3, 0);
                 listView1.Visible = false;
                 W = listView1.Width + 90;
                 H = 25;
             }
             this.Height = listView1.Height;
//             this.Width = listView1.Width;
//             this.Height = listView1.Height;
//             Bitmap BGRB = new Bitmap(PopUpFormBgr, flowLayoutPanel1.Width + 4, flowLayoutPanel1.Height + 4);
             Bitmap BGRB = FlyBGR(Menu1S, 60, W, H);
             IntPtr hr = IntPtr.Zero;
             G.SetBitmap(BGRB);
             BGRB.Dispose();
             if (sv.Version.Major == 6)
             {
                 hr = WindowsAPI.CreateRoundRectRgn(52, 33, W - 20, H - 10, 10, 10);

             }
             WindowsAPI.DWM_BLURBEHIND dbb;
             dbb.fEnable = true;
             dbb.dwFlags = 1 | 2;
             dbb.hRgnBlur = hr;
             dbb.fTransitionOnMaximized = false;
             
             if (sv.Version.Major == 6)
             {
                 WindowsAPI.DwmEnableBlurBehindWindow(G.Handle, ref dbb);
             }
                
            

        }

         void T_Click(object sender, EventArgs e)
         {
             if ((sender as PictureBox).Name != "Pin")
             {
                 string line = null;
                 string lline = null;
                 List<string> sr = new List<string>();
                 List<string> srr = new List<string>();
                 string txt = "";
                 if (((ButtonState)((sender as PictureBox).Tag)).Pinned != 1)
                 {
                     if (Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])).ToLower() != "firefox")
                     {
                         pinnedTableAdapter.Insert(
                                     Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                                     ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[2].Text);
                     }
                     else
                     {
                         pinnedTableAdapter.Insert(
                                      Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                                      ((ButtonState)((sender as PictureBox).Tag)).l.Text + "*" + ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[2].Text);
                     }
                     pinnedTableAdapter.Update(ds1.Pinned);
                     ds1.AcceptChanges();
                     ButtonState bb = new ButtonState();
                     bb.l = ((ButtonState)((sender as PictureBox).Tag)).l;
                     bb.Pinned = 1;
                     ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[3].Text = "1";

                     (sender as PictureBox).Tag = bb;
                     (sender as PictureBox).Image = PinClearS;
                 }
                 else
                 {
                     //                if (Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])).ToLower() == "firefox")
                     //                {
                     if (Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])).ToLower() != "firefox")
                     {
                         pinnedTableAdapter.DeleteQ(
                                          Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                                          ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[2].Text); 
                     }
                     else
                     {
                         pinnedTableAdapter.DeleteQ(
                                           Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                                           ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[2].Text + ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[5].Text); 
                     }
                     //                }
                     //                else
                     //                {
                     //                    pinnedTableAdapter.DeleteQ(
                     //                          Path.GetFileNameWithoutExtension(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                     //                          ((ButtonState)((sender as PictureBox).Tag)).l.Text);  
                     //                }
                     pinnedTableAdapter.Update(ds1.Pinned);
                     ds1.AcceptChanges();
                     ButtonState bb = new ButtonState();
                     bb.l = ((ButtonState)((sender as PictureBox).Tag)).l;
                     bb.Pinned = 0;
                     ((ButtonState)((sender as PictureBox).Tag)).l.SubItems[3].Text = "0";
                     (sender as PictureBox).Tag = bb;
                     (sender as PictureBox).Image = UnPinClearS;
                 } 
             }
         }

         void T_MouseLeave(object sender, EventArgs e)
         {
             if (((ButtonState)((sender as PictureBox).Tag)).Pinned != 1)
             {
                 (sender as PictureBox).Image = UnPinClearS; 
             }
             else
             {
                 (sender as PictureBox).Image = PinClearS;   
             }
         }

         void T_MouseHover(object sender, EventArgs e)
         {
             if (((ButtonState)((sender as PictureBox).Tag)).Pinned != 1)
             {
                 (sender as PictureBox).Image = UnPin;
             }
             else
             {
                 (sender as PictureBox).Image = PinS;
             }
         }
         private Bitmap CopyBitmap(Bitmap source, Rectangle part)
         {
             Bitmap bmp = new Bitmap(part.Width, part.Height);
             Graphics g = Graphics.FromImage(bmp);
             g.DrawImage(source, 0, 0, part, GraphicsUnit.Pixel);
             g.Dispose();
             return bmp;
         }
         public Bitmap FlyBGR(Bitmap B, int Dev, int Wi, int He)
         {
             Bitmap B1 = CopyBitmap(B, new Rectangle(0, 0, Dev, Dev));
             Bitmap B2 = CopyBitmap(B, new Rectangle(B.Width - Dev, 0, Dev, Dev));
             Bitmap B3 = CopyBitmap(B, new Rectangle(0, B.Height - Dev, Dev, Dev));
             Bitmap B4 = CopyBitmap(B, new Rectangle(B.Width - Dev, B.Height - Dev, Dev + 10, Dev + 10));
             Bitmap B1L = CopyBitmap(B, new Rectangle(0, Dev + 15, Dev, 1));
             Bitmap B1R = CopyBitmap(B, new Rectangle(B.Width - Dev, Dev + 15, Dev, 1));
             Bitmap B1U = CopyBitmap(B, new Rectangle(Dev + 15, 0, 1, Dev));
             Bitmap B1D = CopyBitmap(B, new Rectangle(Dev + 15, B.Height - Dev, 1, Dev));
             Bitmap BG = CopyBitmap(B, new Rectangle(Dev + 25, Dev + 25, Dev + 25, Dev + 25));
             Bitmap BB = new Bitmap(Wi, He);
             BB.MakeTransparent();
             Graphics g = Graphics.FromImage(BB);
             Brush tBrush = new TextureBrush(BG);

             for (int i = 0; i < Wi - Dev * 2; i++)
             {
                 g.DrawImage(B1U, Dev + i, 0);
                 g.DrawImage(B1D, Dev + i, He - Dev);
             }
             for (int j = 0; j < He - Dev * 2; j++)
             {
                 g.DrawImage(B1L, 0, Dev + j);
                 g.DrawImage(B1R, Wi - Dev, Dev + j);
             }
             g.DrawImage(B1, 0, 0);
             g.DrawImage(B2, BB.Width - Dev, 0);
             g.DrawImage(B3, 0, BB.Height - Dev);
             g.DrawImage(B4, BB.Width - Dev, BB.Height - Dev);


             g.FillRectangle(tBrush, Dev, Dev, Wi - Dev * 2, He - Dev * 2);
             B1.Dispose();
             B2.Dispose();
             B3.Dispose();
             B4.Dispose();
             B1L.Dispose();
             B1R.Dispose();
             B1U.Dispose();
             B1D.Dispose();
             BG.Dispose();
             g.Dispose();
             tBrush.Dispose();
             return BB;
         }
        
        private void PopUpForm_MouseUp(object sender, MouseEventArgs e)
        {
            
        }
        public string GetAssoc(string doctype)
        {

            uint pcchOut = 0;
            WindowsAPI.AssocQueryString(WindowsAPI.AssocF.Verify, WindowsAPI.AssocStr.Executable, doctype, null, null, ref pcchOut);
            StringBuilder pszOut = new StringBuilder((int)pcchOut);
            WindowsAPI.AssocQueryString(WindowsAPI.AssocF.Verify, WindowsAPI.AssocStr.Executable, doctype, null, pszOut, ref pcchOut);
            return pszOut.ToString();
        }

        private void imageButton1_Click(object sender, EventArgs e)
        {
            foreach (IntPtr ptr in Handles)
            {
                WindowsAPI.PostMessage(ptr, WindowsAPI.WM_SYSCOMMAND, (IntPtr)WindowsAPI.SC_CLOSE, IntPtr.Zero);
            }
            this.Owner.Dispose();
        }

        private void PopUpForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (Control c in Controls)
            {
                c.Dispose();
            }
            GC.Collect();
        }

        private void imageButton2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(WindowsAPI.GetWindowModuleFileName(Handles[0]));
            this.Owner.Close();
        }

        private void flowLayoutPanel1_Leave(object sender, EventArgs e)
        {
            
        }

        private void flowLayoutPanel1_MouseLeave(object sender, EventArgs e)
        {
            Timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Owner.Close();
        }
        public OperatingSystemVersion sv = new OperatingSystemVersion();
        public ImageButton IB = new ImageButton();
        private void PopUpForm_Load(object sender, EventArgs e)
        {
            
            // TODO: This line of code loads data into the 'ds1.Pinned' table. You can move, or remove it, as needed.
            this.pinnedTableAdapter.Fill(this.ds1.Pinned);
            
            CustomImagelist.Images.Clear();
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\PresenceOnline_16x16.png",CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\PresenceAway_16x16.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\PresenceDoNotDisturb_16x16.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\PresenceOffline_16x16.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\PresenceOffline_16x16.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\PresenceAvailable_16x16.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\MSNOnline.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\MSNAway.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\MSNBusy.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\MSNOffline.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\MSN.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\WMPPlay.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\WMPStop.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\WMP.png", CustomImagelist);
            Imagelist.AddFromFile(ExePath + "\\Skins\\" + SkinDir + "\\WMPPause.png", CustomImagelist);
            
            if (sv.OSMajorVersion == 6)
            {
                WindowsAPI.SetWindowTheme(listView1.Handle, "explorer", null);
                listView1.Refresh(); 
            }
            Timer1.Stop();
        }

        private void flowLayoutPanel1_MouseHover(object sender, EventArgs e)
        {
            Timer1.Stop();
        }

        private void imageButton2_MouseHover(object sender, EventArgs e)
        {
            Timer1.Stop();
        }

        private void imageButton1_MouseHover(object sender, EventArgs e)
        {
            Timer1.Stop();
        }

        private void PopUpForm_MouseHover(object sender, EventArgs e)
        {
            Timer1.Stop();
        }

        private void listView1_MouseHover(object sender, EventArgs e)
        {
            Timer1.Stop();
        }

        private void PopUpForm_Shown(object sender, EventArgs e)
        {
//            pictureBox1.Location = new Point(0,0);
        }

        private void listView1_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            if (sv.OSMajorVersion != 6)
            {
                pictureBox1.BringToFront();
                Bitmap u = new Bitmap(ExePath + "\\Skins\\" + SkinDir + "\\1.png");
                Rectangle r = e.Item.Bounds;
                Bitmap b;
                if (e.Item.Group != listView1.Groups[3])
                {
                    b = new Bitmap(u, this.Width - 26, r.Height);
                }
                else
                {
                    b = new Bitmap(u, this.Width - 15, r.Height);
                }
                Graphics g = Graphics.FromImage(b);
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
                System.Drawing.Icon I = null;
                if (listView1.SmallImageList != CustomImagelist)
                {
                    I = sysimage.Icon(e.Item.ImageIndex); 
                }
                else
                {
                    I = Icon.FromHandle(((Bitmap)CustomImagelist.Images[e.Item.ImageIndex]).GetHicon());
                }
                g.DrawString(e.Item.Text, listView1.Font, Brushes.Black, 16, 4);
                g.DrawIcon(I, 0, 2);
                pictureBox1.Image = b;
                if (e.Item.Group != listView1.Groups[3] | e.Item.Group != listView1.Groups[2])
                {
                    pictureBox1.Width = this.Width - 26; 
                }
                else
                {
                    pictureBox1.Width = this.Width - 15;  
                }
                pictureBox1.Tag = e.Item;
                pictureBox1.Height = r.Height;
                pictureBox1.Location = new Point(r.X + 6, r.Y + r.Height / 2 - 8);
                pictureBox1.Visible = true; 
            }
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            ListViewItem LI = (sender as PictureBox).Tag as ListViewItem;
            try
            {
                if (LI.SubItems[1].Text == "")
                {
                    WindowsAPI.ShellExecute(IntPtr.Zero, "open", LI.SubItems[2].Text, "", "",
                                                    WindowsAPI.ShowCommands.SW_SHOWNOACTIVATE);
                }
                else if (LI.SubItems[1].Text.ToLower() == "explorer")
                {
                    Process.Start(LI.SubItems[2].Text);
                }
                else if (LI.SubItems[1].Text.ToLower() == "firefox")
                {
                    int h = LI.SubItems[5].Text.IndexOf("*");
                    string s = LI.SubItems[5].Text.Substring(1);
                    Process.Start(FirefoxPath,s);
                }
                else if (LI.SubItems[1].Text.ToLower() == "sysclose")
                {
                    foreach (IntPtr ptr in Handles)
                    {
                        WindowsAPI.PostMessage(ptr, WindowsAPI.WM_SYSCOMMAND, (IntPtr)WindowsAPI.SC_CLOSE, IntPtr.Zero);
                    }
                    this.Owner.Dispose();
                }
                else if (LI.SubItems[1].Text.ToLower() == "opennew")
                {
                    System.Diagnostics.Process.Start(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                    this.Owner.Close();
                }
                else if (LI.SubItems[1].Text.ToLower() == "pintaskbar")
                {
                    if (IsPinned == 0)
                    {
                        int MAx = 1;
                        try
                        {
                            MAx = (int)taskbarPinnedTableAdapterpu.MAXCODE() + 1;
                        }
                        catch 
                        {
                            MAx = 1;
                        }
                        taskbarPinnedTableAdapterpu.Insert(
                                        Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                                        WindowsAPI.GetWindowModuleFileName(Handles[0]), MAx);
                        taskbarPinnedTableAdapterpu.Update(ds1.TaskbarPinned);
                        ds1.AcceptChanges();
                        foreach (Control ctrl in this.Controls)
                        {
                            if (ctrl.Name == "Pin")
                            {
                                PictureBox pb = ctrl as PictureBox;
                                pb.Image = PinClearS;
                            }
                        }
//                        taskbarPinnedTableAdapterpu.Fill(ds1.TaskbarPinned);
                        string s = "";
                        try
                        {
                            s = Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                        }
                        catch
                        {

                            s = Path.GetFileName(PinExePath);
                        }
                        TRV.GetItemAt(s).SubItems[7].Text = "1";
                    }
                    else
                    {
                        try
                        {
                            taskbarPinnedTableAdapterpu.DeletePin(
                                                Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0])));
                        }
                        catch
                        {
                            taskbarPinnedTableAdapterpu.DeletePin(Path.GetFileName(PinExePath));
                        }
                        taskbarPinnedTableAdapterpu.Update(ds1.TaskbarPinned);
                        ds1.AcceptChanges();
                        foreach (Control ctrl in this.Controls)
                        {
                            if (ctrl.Name == "Pin")
                            {
                                PictureBox pb = ctrl as PictureBox;
                                pb.Image = UnPinClearS;
                            }
                        }
                        string s = "";
                        try 
                        {
                            s = Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                        }
                        catch
                        {

                            s = Path.GetFileName(PinExePath);
                        }
                        TRV.GetItemAt(s).SubItems[7].Text = "0";
                        if (TRV.GetItemAt(s).Nodes.Count == 0)
                        {
                            TreeListNode TTT = null;
                            int PosH = -1;
                            PerPixelAlphaForm FF =
                                FromHandle((IntPtr) Convert.ToInt32(TRV.GetItemAt(s).SubItems[0].Text)) as PerPixelAlphaForm;
                            FF.Dispose();
                            for (int j = 0; j < TRV.Nodes.Count; j++)
                            {
                                string ff = TRV.Nodes[j].Text;


                                if (ff.ToLowerInvariant() == s.ToLowerInvariant())
                                {
                                    TTT = TRV.Nodes[j];
                                    PosH = TRV.Nodes.IndexOf(TRV.Nodes[j]);
                                    

                                }


                            }
                            for (int i = PosH; i < TRV.Nodes.Count - 1; i++)
                            {
                                Form MF;
                                Form MIF;
                                Form MC;

                                MF = FromHandle((IntPtr)Convert.ToInt32(TRV.Nodes[i + 1].SubItems[0].Text)) as Form;

                                MF.Location = new Point(MF.Location.X - MF.Width - 2, MF.Location.Y);

                                MIF = FromHandle((IntPtr)Convert.ToInt32(TRV.Nodes[i + 1].SubItems[1].Text)) as Form;

                                MIF.Location = new Point(MIF.Location.X - MF.Width - 2, MIF.Location.Y);

                                try
                                {
                                    MC = FromHandle((IntPtr)Convert.ToInt32(TRV.Nodes[i + 1].SubItems[5].Text)) as Form;

                                    MC.Location = new Point(MC.Location.X - MF.Width - 2, MC.Location.Y);
                                }
                                catch
                                {

                                }
                            }
                            TRV.Nodes.RemoveAt(TRV.Nodes.IndexOf(TRV.GetItemAt(s)));

                        }
//                        taskbarPinnedTableAdapterpu.Fill(ds1.TaskbarPinned);
                    }
                }
                else if (LI.SubItems[1].Text.ToLower() == "skype")
                {
                    switch (LI.SubItems[2].Text)
                    {
                        case "O":
                            Sky.ChangeUserStatus(TUserStatus.cusOnline);
                            break;
                        case "A":
                            Sky.ChangeUserStatus(TUserStatus.cusAway);
                            break;
                        case "I":
                            Sky.ChangeUserStatus(TUserStatus.cusInvisible);
                            break;
                        case "NA":
                            Sky.ChangeUserStatus(TUserStatus.cusDoNotDisturb);
                            break;
                        case "F":
                            Sky.ChangeUserStatus(TUserStatus.cusOffline);
                            break;
                    } 
                }
                else if (LI.SubItems[1].Text.ToLower() == "mplay")
                {
                    switch (LI.SubItems[2].Text)
                    {
                        case "P":
                            if (MediaPLayeH != IntPtr.Zero)
                            {
                                WindowsAPI.SendMessage(MediaPLayeH, (int)WindowsAPI.WndMsg.WM_COMMAND, 0x00004978, 0x00000000); 
                            }
                            break;
                        case "S":
                            if (MediaPLayeH != IntPtr.Zero)
                            {
                                WindowsAPI.SendMessage(MediaPLayeH, (int)WindowsAPI.WndMsg.WM_COMMAND, 0x00004979, 0x00000000);
                            }
                            break;
                    }
                }
                else if (LI.SubItems[1].Text.ToLower() == "msn")
                {
                    switch (LI.SubItems[2].Text)
                    {
                        case "O":
                            MSN.MyStatus = MISTATUS.MISTATUS_ONLINE;
                            break;
                        case "A":
                            MSN.MyStatus = MISTATUS.MISTATUS_AWAY;
                            break;
                        case "I":
                            MSN.MyStatus = MISTATUS.MISTATUS_INVISIBLE;
                            break;
                        case "NA":
                            MSN.MyStatus = MISTATUS.MISTATUS_BUSY;
                            break;
                    }
                }
            }
            catch
            {

            }
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (sv.OSMajorVersion == 6)
            {
                try
                {
                    ListViewItem LI = e.Item;
                    try
                    {
                        if (LI.SubItems[1].Text == "")
                        {
                            WindowsAPI.ShellExecute(IntPtr.Zero, "open", LI.SubItems[2].Text, "", "",
                                                            WindowsAPI.ShowCommands.SW_SHOWNOACTIVATE);
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "explorer")
                        {
                            Process.Start(LI.SubItems[2].Text);
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "firefox")
                        {
                            //                        if (LI.SubItems[2].Text != "-new-tab")
                            //                        {
                            Process.Start(FirefoxPath, LI.SubItems[2].Text);
                            //                        }
                            //                        else
                            //                        {
                            //                            this.Owner.Dispose();
                            //                            WindowsAPI.SetWindowPos(Handles[0], WindowsAPI.HWND_TOPMOST, 0, 0, 0, 0,
                            //                                                    WindowsAPI.SWP_NOSIZE | WindowsAPI.SWP_NOMOVE |
                            //                                                    WindowsAPI.SWP_SHOWWINDOW);
                            ////                            WindowsAPI.SetActiveWindow(Handles[0]);
                            //                            SendKeys.Send("^T");
                            //                        }
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "pintaskbar")
                        {
                            if (IsPinned == 0)
                            {
                                int MAx = 1;
                                try
                                {
                                    MAx = (int) taskbarPinnedTableAdapterpu.MAXCODE() + 1;
                                }
                                catch
                                {
                                    MAx = 1;
                                }
                                taskbarPinnedTableAdapterpu.Insert(
                                    Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0])),
                                    WindowsAPI.GetWindowModuleFileName(Handles[0]), MAx);
                                taskbarPinnedTableAdapterpu.Update(ds1.TaskbarPinned);
                                ds1.AcceptChanges();
                                foreach (Control ctrl in this.Controls)
                                {
                                    if (ctrl.Name == "Pin")
                                    {
                                        PictureBox pb = ctrl as PictureBox;
                                        pb.Image = PinClearS;
                                    }
                                }
                                //                        taskbarPinnedTableAdapterpu.Fill(ds1.TaskbarPinned);
                                string s = "";
                                try
                                {
                                    s = Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                                }
                                catch
                                {

                                    s = Path.GetFileName(PinExePath);
                                }
                                TRV.GetItemAt(s).SubItems[7].Text = "1";
                            }
                            else
                            {
                                try
                                {
                                    taskbarPinnedTableAdapterpu.DeletePin(
                                        Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0])));
                                }
                                catch
                                {
                                    taskbarPinnedTableAdapterpu.DeletePin(Path.GetFileName(PinExePath));
                                }
                                taskbarPinnedTableAdapterpu.Update(ds1.TaskbarPinned);
                                ds1.AcceptChanges();
                                foreach (Control ctrl in this.Controls)
                                {
                                    if (ctrl.Name == "Pin")
                                    {
                                        PictureBox pb = ctrl as PictureBox;
                                        pb.Image = UnPinClearS;
                                    }
                                }
                                string s = "";
                                try
                                {
                                    s = Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                                }
                                catch
                                {

                                    s = Path.GetFileName(PinExePath);
                                }
                                TRV.GetItemAt(s).SubItems[7].Text = "0";
                                if (TRV.GetItemAt(s).Nodes.Count == 0)
                                {
                                    TreeListNode TTT = null;
                                    int PosH = -1;
                                    PerPixelAlphaForm FF =
                                        FromHandle((IntPtr) Convert.ToInt32(TRV.GetItemAt(s).SubItems[0].Text)) as
                                        PerPixelAlphaForm;
                                    FF.Dispose();
                                    for (int j = 0; j < TRV.Nodes.Count; j++)
                                    {
                                        string ff = TRV.Nodes[j].Text;


                                        if (ff.ToLower() == s.ToLower())
                                        {
                                            TTT = TRV.Nodes[j];
                                            PosH = TRV.Nodes.IndexOf(TRV.Nodes[j]);


                                        }


                                    }
                                    for (int i = PosH; i < TRV.Nodes.Count - 1; i++)
                                    {
                                        Form MF;
                                        Form MIF;
                                        Form MC;

                                        MF =
                                            FromHandle((IntPtr) Convert.ToInt32(TRV.Nodes[i + 1].SubItems[0].Text)) as
                                            Form;

                                        MF.Location = new Point(MF.Location.X - MF.Width - 2, MF.Location.Y);

                                        MIF =
                                            FromHandle((IntPtr) Convert.ToInt32(TRV.Nodes[i + 1].SubItems[1].Text)) as
                                            Form;

                                        MIF.Location = new Point(MIF.Location.X - MF.Width - 2, MIF.Location.Y);

                                        try
                                        {
                                            MC =
                                                FromHandle((IntPtr) Convert.ToInt32(TRV.Nodes[i + 1].SubItems[5].Text))
                                                as Form;

                                            MC.Location = new Point(MC.Location.X - MF.Width - 2, MC.Location.Y);
                                        }
                                        catch
                                        {

                                        }
                                    }
                                    TRV.Nodes.RemoveAt(TRV.Nodes.IndexOf(TRV.GetItemAt(s)));

                                }
                                //                        taskbarPinnedTableAdapterpu.Fill(ds1.TaskbarPinned);
                            }
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "skype")
                        {
                            //                            Process.LeaveDebugMode();
                            //                            Sky.Protocol = 8;
                            switch (LI.SubItems[2].Text)
                            {
                                case "O":
                                    Sky.ChangeUserStatus(TUserStatus.cusOnline);
                                    break;
                                case "A":
                                    Sky.ChangeUserStatus(TUserStatus.cusAway);
                                    break;
                                case "I":
                                    Sky.ChangeUserStatus(TUserStatus.cusInvisible);
                                    break;
                                case "NA":
                                    Sky.ChangeUserStatus(TUserStatus.cusDoNotDisturb);
                                    break;
                                case "F":
                                    Sky.ChangeUserStatus(TUserStatus.cusOffline);
                                    break;
                            }
                                   
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "mplay")
                        {
                            switch (LI.SubItems[2].Text)
                            {
                                case "P":
                                    if (MediaPLayeH != IntPtr.Zero)
                                    {
                                        WindowsAPI.SendMessage(MediaPLayeH, (int)WindowsAPI.WndMsg.WM_COMMAND, 0x00004978, 0x00000000);
                                    }
                                    break;
                                case "S":
                                    if (MediaPLayeH != IntPtr.Zero)
                                    {
                                        WindowsAPI.SendMessage(MediaPLayeH, (int)WindowsAPI.WndMsg.WM_COMMAND, 0x00004979, 0x00000000);
                                    }
                                    break;
                            }
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "msn")
                        {
                            switch (LI.SubItems[2].Text)
                            {
                                case "O":
                                    MSN.MyStatus = MISTATUS.MISTATUS_ONLINE;
                                    break;
                                case "A":
                                    MSN.MyStatus = MISTATUS.MISTATUS_AWAY;
                                    break;
                                case "I":
                                    MSN.MyStatus = MISTATUS.MISTATUS_INVISIBLE;
                                    break;
                                case "NA":
                                    MSN.MyStatus = MISTATUS.MISTATUS_BUSY;
                                    break;
                            }
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "sysclose")
                        {
                            foreach (IntPtr ptr in Handles)
                            {
                                WindowsAPI.PostMessage(ptr, WindowsAPI.WM_SYSCOMMAND, (IntPtr)WindowsAPI.SC_CLOSE, IntPtr.Zero);
                            }
                            this.Owner.Dispose();
                        }
                        else if (LI.SubItems[1].Text.ToLower() == "opennew")
                        {
                            System.Diagnostics.Process.Start(WindowsAPI.GetWindowModuleFileName(Handles[0]));
                            this.Owner.Close();
                        }
                    }
                    catch
                    {

                    }
                }
                catch
                {

                } 
            }
        }

        private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            MessageBox.Show("h");
        }
        
    }
}
